package com.suxii.frpclient.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.suxii.frpclient.R;
import com.suxii.frpclient.adapter.LogAdapter;
import com.suxii.frpclient.databinding.FragmentHomeBinding;
import com.suxii.frpclient.databinding.FragmentLogBinding;
import com.suxii.frpclient.message.NavStateMessage;
import com.suxii.frpclient.message.TaskRunningMessage;
import com.suxii.frpclient.service.FrpService;
import com.suxii.frpclient.utils.RxBus;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;

public class LogFragment extends Fragment {


    public static final String NAME = "LOG";

    public static LogFragment newInstance() {
        LogFragment fragment = new LogFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    private final CompositeDisposable compositeDisposable = new CompositeDisposable();

    private FragmentLogBinding binding;

    private LogAdapter logAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentLogBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        initEvent();
        return view;
    }

    private boolean state;

    private void initEvent(){
        logAdapter = new LogAdapter(requireContext());
        binding.logList.setLayoutManager(new LinearLayoutManager(requireContext()));
        binding.logList.setAdapter(logAdapter);

        binding.title.setOnLongClickListener(v -> {
            RxBus.getInstance().post(new NavStateMessage(state));
            state = !state;
            return true;
        });


        // 订阅 RxBus 中的数据
        Disposable disposable = RxBus.getInstance().toObservable(TaskRunningMessage.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(data -> {
//                    binding.title.setText(data);
                    logAdapter.addData(data.getData());
                    if (!data.isRun()) {
                        Intent intent = new Intent(requireContext(), FrpService.class);
                        boolean exit = requireContext().stopService(intent);
                        Toast.makeText(requireContext(), "退出服务："+exit, Toast.LENGTH_SHORT).show();
                    }
                });

        compositeDisposable.add(disposable);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        compositeDisposable.clear();
    }
}